package com.openness.spider.zk;

import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;

/**
 * @author Rain
 * @version 2013-6-20 下午3:37:08
 */

public class ZKUtil {

	private static final ProtocolSupport PROTOCOL = new ProtocolSupport();

	public static String create(final ZooKeeper zk, final String path,
			final byte[] data, final List<ACL> acl, final CreateMode createMode)
			throws Exception {
		return PROTOCOL.retryOperation(new ZooKeeperOperation<String>() {

			@Override
			public String execute() throws Exception {
				return zk.create(path, data, acl, createMode);
			}

		});
	}

	public static boolean delete(final ZooKeeper zk, final String path,
			final int version) throws Exception {
		return PROTOCOL.retryOperation(new ZooKeeperOperation<Boolean>() {

			@Override
			public Boolean execute() throws Exception {
				zk.delete(path, version);

				return true;
			}

		});
	}

	public static boolean exists(final ZooKeeper zk, final String path,
			final boolean watch) throws Exception {
		return PROTOCOL.retryOperation(new ZooKeeperOperation<Boolean>() {

			@Override
			public Boolean execute() throws Exception {
				return zk.exists(path, watch) != null ? true : false;
			}

		});
	}

	public static List<String> getChildren(final ZooKeeper zk,
			final String path, final boolean watch) throws Exception {
		return PROTOCOL.retryOperation(new ZooKeeperOperation<List<String>>() {

			@Override
			public List<String> execute() throws Exception {
				return zk.getChildren(path, watch);
			}

		});
	}

}
